package com.business_clean.ui.activity.roster

import android.os.Bundle
import android.text.TextUtils
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.LogUtils
import com.business_clean.R
import com.business_clean.app.App
import com.business_clean.app.base.BaseActivity
import com.business_clean.app.ext.CommonUtils
import com.business_clean.app.ext.CommonUtils.showDialogDoubleTimePickerPopup
import com.business_clean.app.ext.initGridLayoutManager
import com.business_clean.data.mode.roster.RosterFilterData
import com.business_clean.databinding.ActivityRosterFilterBinding
import com.business_clean.ui.activity.custom.AddProjectActivity
import com.business_clean.ui.adapter.BaseStringAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import me.hgj.mvvmhelper.base.BaseViewModel
import me.hgj.mvvmhelper.ext.toast
import java.util.Calendar

class RosterFilterActivity : BaseActivity<BaseViewModel, ActivityRosterFilterBinding>() {

    private var mSexAdapter = BaseStringAdapter(1)// 性别
    private var mStartAdapter = BaseStringAdapter(1) // 合同开始时间
    private var mEndAdapter = BaseStringAdapter(1) // 合同结束时间
    private var mContractAdapter = BaseStringAdapter(1) // 合同类型
    private var mPicAdapter = BaseStringAdapter(1) // 头像
    private var mBankAdapter = BaseStringAdapter(1) // 银行卡
    private var mCreditInquiryAdapter = BaseStringAdapter(1) // 信用查询
    private var mInsureAdapter = BaseStringAdapter(1) //保险
    private var mContractStatusAdapter = BaseStringAdapter(1) //合同
    private var mHealthAdapter = BaseStringAdapter(1) //合同
    private var mRecordCheckAdapter = BaseStringAdapter(1) //犯罪记录

    private var isStartSelect: Boolean = false
    private var isEndSelect: Boolean = false


    private var isReset = false


    override fun initView(savedInstanceState: Bundle?) {
        initData()
        mDatabind.recyclerviewSex.initGridLayoutManager(this, bindAdapter = mSexAdapter, spanCount = 2)
        mDatabind.recyclerviewStartDate.initGridLayoutManager(this, bindAdapter = mStartAdapter, spanCount = 4)
        mDatabind.recyclerviewEndDate.initGridLayoutManager(this, bindAdapter = mEndAdapter, spanCount = 4)
        mDatabind.recyclerviewContract.initGridLayoutManager(this, bindAdapter = mContractAdapter, spanCount = 3)
        mDatabind.recyclerviewPic.initGridLayoutManager(this, bindAdapter = mPicAdapter, spanCount = 3)
        mDatabind.recyclerviewBank.initGridLayoutManager(this, bindAdapter = mBankAdapter, spanCount = 3)
        mDatabind.recyclerviewCreditInquiry.initGridLayoutManager(this, bindAdapter = mCreditInquiryAdapter, spanCount = 3)
        mDatabind.recyclerviewInsure.initGridLayoutManager(this, bindAdapter = mInsureAdapter, spanCount = 3)
        mDatabind.recyclerviewContractStatus.initGridLayoutManager(this, bindAdapter = mContractStatusAdapter, spanCount = 3)
        mDatabind.recyclerviewHealth.initGridLayoutManager(this, bindAdapter = mHealthAdapter, spanCount = 3)
        mDatabind.recyclerviewRecordCheck.initGridLayoutManager(this, bindAdapter = mRecordCheckAdapter, spanCount = 3)
    }

    /**
     * set 数据
     */
    private fun initData() {
        val sexArray = ArrayList<String>()
        sexArray.add("男")
        sexArray.add("女")
        mSexAdapter.setList(sexArray)

        val dateArr = java.util.ArrayList<String>()
        dateArr.add("上周")
        dateArr.add("本周")
        dateArr.add("本月")
        dateArr.add("下月")
        mStartAdapter.setList(dateArr)
        mEndAdapter.setList(dateArr)

        val contractArray = ArrayList<String>()
        contractArray.add("劳务合同")
        contractArray.add("退休返聘合同")
        mContractAdapter.setList(contractArray)

        val picArray = ArrayList<String>()
        picArray.add("未完善")
        picArray.add("已完善")
        mPicAdapter.setList(picArray)
        mHealthAdapter.setList(picArray)
        mRecordCheckAdapter.setList(picArray)

        val bankArray = ArrayList<String>()
        bankArray.add("未完善")
//        bankArray.add("异常")
        bankArray.add("已完善")
        mBankAdapter.setList(bankArray)

        val creditInquiryArr = ArrayList<String>()
        creditInquiryArr.add("异常")
        creditInquiryArr.add("正常")
        mCreditInquiryAdapter.setList(creditInquiryArr)

        val insureArr = ArrayList<String>()
        insureArr.add("未购买")
        insureArr.add("已购买")
        mInsureAdapter.setList(insureArr)

        val contractArr = ArrayList<String>()
        contractArr.add("未完善")
        contractArr.add("签署中")
        contractArr.add("已完善")
        mContractStatusAdapter.setList(contractArr)

        val filterData = App.appViewModelInstance.filterRosterFilterData.value
        if (filterData != null) {
            LogUtils.e("不等于的$filterData")

            //这里是性别
            if (!TextUtils.isEmpty(filterData.sex)) {
                mSexAdapter.updateItem(filterData.sex?.toInt()!! - 1)
            }

            //这里是最小年龄
            if (!TextUtils.isEmpty(filterData.min_age)) {
                mDatabind.tvMinAgeResult.text = filterData.min_age + "岁"
                changeButtonSelected(mDatabind.tvMinAgeResult, true)
            }

            //这里是最大年龄
            if (!TextUtils.isEmpty(filterData.max_age)) {
                mDatabind.tvMaxAgeResult.text = filterData.max_age + "岁"
                changeButtonSelected(mDatabind.tvMaxAgeResult, true)
            }

            //合约开始日期
            if (!TextUtils.isEmpty(filterData.start_date)) {
                invertDateData(mDatabind.tvStartDateResult, filterData.start_date, mStartAdapter)
            }

            //合约结束日期
            if (!TextUtils.isEmpty(filterData.end_date)) {
                invertDateData(mDatabind.tvEndDateResult, filterData.end_date, mEndAdapter)
            }

            //这里是合同类型
            if (!TextUtils.isEmpty(filterData.contract_type)) {
                mContractAdapter.updateItem(filterData.contract_type?.toInt()!! - 1)
            }

            //这里是头像
            if (!TextUtils.isEmpty(filterData.pic_status)) {
                mPicAdapter.updateItem(filterData.pic_status?.toInt()!! - 1)
            }

            //这里是银行卡
            if (!TextUtils.isEmpty(filterData.bank_status)) {
                mBankAdapter.updateItem(filterData.bank_status?.toInt()!! - 1)
            }

            //这里是信用查询
            if (!TextUtils.isEmpty(filterData.credit_inquiry_status)) {
                mCreditInquiryAdapter.updateItem(filterData.credit_inquiry_status?.toInt()!! - 1)
            }

            //这里是合同
            if (!TextUtils.isEmpty(filterData.contract_status)) {
                mContractStatusAdapter.updateItem(filterData.contract_status?.toInt()!! - 1)
            }

            //这里是健康证明
            if (!TextUtils.isEmpty(filterData.health_status)) {
                mHealthAdapter.updateItem(filterData.health_status?.toInt()!! - 1)
            }

            //这里是无犯罪证明
            if (!TextUtils.isEmpty(filterData.recode_check)) {
                mRecordCheckAdapter.updateItem(filterData.recode_check?.toInt()!! - 1)
            }

        }


    }


    override fun onBindViewClick() {
        mSexAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mSexAdapter.updateItem(position)
            isReset = false
        })

        mStartAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mStartAdapter.updateItem(position)
            isStartSelect = false
            mDatabind.tvStartDateResult.text = "自定义日期范围"
            changeButtonSelected(mDatabind.tvStartDateResult, isSelected = false)
            isReset = false
        })

        mEndAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mEndAdapter.updateItem(position)
            isEndSelect = false
            mDatabind.tvEndDateResult.text = "自定义日期范围"
            changeButtonSelected(mDatabind.tvEndDateResult, isSelected = false)
            isReset = false
        })

        mContractAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mContractAdapter.updateItem(position)
            isReset = false
        })

        mDatabind.tvStartDateResult.setOnClickListener {
            dateResult(true)
            isReset = false
        }

        mDatabind.tvEndDateResult.setOnClickListener {
            dateResult(false)
            isReset = false
        }

        mDatabind.tvMinAgeResult.setOnClickListener {
            if (mDatabind.tvMinAgeResult.text.toString() == "不限制") {
                showAgeDialog(true)
            } else {
                mDatabind.tvMinAgeResult.text = "不限制"
                changeButtonSelected(mDatabind.tvMinAgeResult, false)
            }
            isReset = false
        }
        mDatabind.tvMaxAgeResult.setOnClickListener {
            if (mDatabind.tvMaxAgeResult.text.toString() == "不限制") {
                showAgeDialog(false)
            } else {
                mDatabind.tvMaxAgeResult.text = "不限制"
                changeButtonSelected(mDatabind.tvMaxAgeResult, false)
            }
            isReset = false
        }

        mPicAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mPicAdapter.updateItem(position)
            isReset = false
        })

        mBankAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mBankAdapter.updateItem(position)
            isReset = false
        })
        mCreditInquiryAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mCreditInquiryAdapter.updateItem(position)
            isReset = false
        })
        mInsureAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mInsureAdapter.updateItem(position)
            isReset = false
        })
        mContractStatusAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mContractStatusAdapter.updateItem(position)
            isReset = false
        })
        mHealthAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mHealthAdapter.updateItem(position)
            isReset = false
        })
        mRecordCheckAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            mRecordCheckAdapter.updateItem(position)
            isReset = false
        })

        //重置所有的筛选条件
        mDatabind.btFilterReset.setOnClickListener {
//            mSexAdapter.cleanSelectIndices()
//            mStartAdapter.cleanSelectIndices()
//            mEndAdapter.cleanSelectIndices()
//            mContractAdapter.cleanSelectIndices()
//            mDatabind.tvMinAgeResult.text = "不限制"
//            changeButtonSelected(mDatabind.tvMinAgeResult, false)
//            mDatabind.tvMaxAgeResult.text = "不限制"
//            changeButtonSelected(mDatabind.tvMaxAgeResult, false)
//            mDatabind.tvStartDateResult.text = "自定义日期范围"
//            changeButtonSelected(mDatabind.tvStartDateResult, isSelected = false)
//            mDatabind.tvEndDateResult.text = "自定义日期范围"
//            changeButtonSelected(mDatabind.tvEndDateResult, isSelected = false)
//            mPicAdapter.cleanSelectIndices()
//            mBankAdapter.cleanSelectIndices()
//            mCreditInquiryAdapter.cleanSelectIndices()
//            mInsureAdapter.cleanSelectIndices()
//            mContractStatusAdapter.cleanSelectIndices()
//            mHealthAdapter.cleanSelectIndices()
//            mRecordCheckAdapter.cleanSelectIndices()
            isReset = true

            val rosterFilterData = RosterFilterData()
            rosterFilterData.isReset = isReset
            App.appViewModelInstance.filterRosterFilterData.value = rosterFilterData
            finish()
        }
        //提交数据给上一层
        mDatabind.btFilterOk.setOnClickListener {
            if (mDatabind.tvMaxAgeResult.text.toString() != "不限制") {
                if (mDatabind.tvMinAgeResult.text.toString() != "不限制") {
                    val minAge = mDatabind.tvMinAgeResult.text.toString().replace("岁", "").toInt()
                    val maxAge = mDatabind.tvMaxAgeResult.text.toString().replace("岁", "").toInt()
                    if (minAge >= maxAge) {
                        "最高年龄必须大于等于最低年龄".toast()
                        return@setOnClickListener
                    }
                }
            }
            val rosterFilterData = RosterFilterData()
            //性别
            rosterFilterData.sex = if (mSexAdapter.singleSelect == -1) "" else "${mSexAdapter.singleSelect + 1}"
            //最小年龄
            rosterFilterData.min_age = if (mDatabind.tvMinAgeResult.text.toString() == "不限制") "" else mDatabind.tvMinAgeResult.text.toString().replace("岁", "")
            //最大年龄
            rosterFilterData.max_age = if (mDatabind.tvMaxAgeResult.text.toString() == "不限制") "" else mDatabind.tvMaxAgeResult.text.toString().replace("岁", "")
            //合约开始日期
            rosterFilterData.start_date = getDateSelect(if (mStartAdapter.singleSelect == -1) "" else mStartAdapter.data[mStartAdapter.singleSelect], mDatabind.tvStartDateResult.text.toString().replace("~", "#"))
            //合约结束日期
            rosterFilterData.end_date = getDateSelect(if (mEndAdapter.singleSelect == -1) "" else mEndAdapter.data[mEndAdapter.singleSelect], mDatabind.tvEndDateResult.text.toString().replace("~", "#"))
            //合同类型
            rosterFilterData.contract_type = if (mContractAdapter.singleSelect == -1) "" else "${mContractAdapter.singleSelect + 1}"
            //是否有投降
            rosterFilterData.pic_status = if (mPicAdapter.singleSelect == -1) "" else "${mPicAdapter.singleSelect + 1}"
            //是否有银行卡
            rosterFilterData.bank_status = if (mBankAdapter.singleSelect == -1) "" else "${mBankAdapter.singleSelect + 1}"
            //是否有健康证
            rosterFilterData.health_status = if (mHealthAdapter.singleSelect == -1) "" else "${mHealthAdapter.singleSelect + 1}"
            //无犯罪证明
            rosterFilterData.recode_check = if (mRecordCheckAdapter.singleSelect == -1) "" else "${mRecordCheckAdapter.singleSelect + 1}"

            rosterFilterData.isReset = isReset

            App.appViewModelInstance.filterRosterFilterData.value = rosterFilterData

            finish()
        }
    }

    //反选开始时间跟结束时间
    private fun invertDateData(textView: TextView, date: String, mAdpater: BaseStringAdapter) {
        if (date.contains("#")) {//说明是自定义的时间
            textView.text = date.replace("#", "~")
            changeButtonSelected(textView, true)
        } else {
            when (date) {
                "lastWeek" -> {
                    mAdpater.updateItem(0)
                }

                "thisWeek" -> {
                    mAdpater.updateItem(1)
                }

                "thisMonth" -> {
                    mAdpater.updateItem(2)
                }

                "nextMonth" -> {
                    mAdpater.updateItem(3)
                }
            }
        }
    }

    /**
     * 这是给后台的值
     */
    private fun getDateSelect(date: String, customDate: String): String {
        var mSelectDate: String = ""
        if (!TextUtils.isEmpty(date)) {
            when (date) {
                "上周" -> {
                    mSelectDate = "lastWeek"
                }

                "本周" -> {
                    mSelectDate = "thisWeek"
                }

                "本月" -> {
                    mSelectDate = "thisMonth"
                }

                "下月" -> {
                    mSelectDate = "nextMonth"
                }
            }
        } else if ("自定义日期范围" != customDate) {
            mSelectDate = customDate
        }
        return mSelectDate
    }


    //改变 自定义日期范围 View 的 状态
    private fun changeButtonSelected(textView: TextView, isSelected: Boolean) {
        textView.setTextColor(if (isSelected) ContextCompat.getColor(this, R.color.base_primary) else ContextCompat.getColor(this, R.color.base_primary_text_title))
        textView.background = (if (isSelected) CommonUtils.getBaseSelectedDrawable(this) else CommonUtils.getBaseUnSelectedDrawable(this))
    }

    //年龄
    private fun showAgeDialog(isMin: Boolean) {
        val ageArray = ArrayList<String>()
        for (i in 18 until 70) {
            ageArray.add("" + i)
        }
        CommonUtils.showDialogWheelSingleList(
            this, if (isMin) "请选择最小年龄" else "请选择最大年龄", ageArray,
            if (isMin) mDatabind.tvMinAgeResult.text.toString().replace("岁", "") else mDatabind.tvMaxAgeResult.text.toString().replace("岁", "")
        ) { position, text ->
            if (isMin) {
                mDatabind.tvMinAgeResult.text = "$text 岁"
            } else {
                mDatabind.tvMaxAgeResult.text = "$text 岁"
            }
            changeButtonSelected(if (isMin) mDatabind.tvMinAgeResult else mDatabind.tvMaxAgeResult, true)
        }
    }

    //日期选择
    private fun dateResult(isStart: Boolean) {
        if (isStart && isStartSelect) {//重置按钮的状态
            isStartSelect = false
            changeButtonSelected(mDatabind.tvStartDateResult, false)
            mDatabind.tvStartDateResult.text = "自定义日期范围"
            return
        }
        if (!isStart && isEndSelect) {//重置按钮的状态
            isEndSelect = false
            changeButtonSelected(mDatabind.tvEndDateResult, false)
            mDatabind.tvEndDateResult.text = "自定义日期范围"
            return
        }

        var cur_start_year = 0
        var cur_start_month = 0
        var cur_start_day = 0
        var cur_stop_year = 0
        var cur_stop_month = 0
        var cur_stop_day = 0

        val calendar = Calendar.getInstance()
        showDialogDoubleTimePickerPopup(
            this, "请选择日期", "确定", "取消", calendar[Calendar.YEAR] - 10,
            calendar[Calendar.YEAR],
            cur_start_year, cur_start_month, cur_start_day,
            cur_stop_year, cur_stop_month, cur_stop_day
        ) { firstTime, secondTime ->
            if (isStart) {
                isStartSelect = true
                mDatabind.tvStartDateResult.text = "${firstTime.replace("-", ".")} ~ ${secondTime.replace("-", ".")}"
                mStartAdapter.cleanSelectIndices()
                changeButtonSelected(mDatabind.tvStartDateResult, isStartSelect)
            } else {
                isEndSelect = true
                mDatabind.tvEndDateResult.text = "${firstTime.replace("-", ".")} ~ ${secondTime.replace("-", ".")}"
                mEndAdapter.cleanSelectIndices()
                changeButtonSelected(mDatabind.tvEndDateResult, isEndSelect)
            }
        }
    }


}